import Drawer from "@src/components/Drawer";
import React, {useEffect} from "react";
import {PlaylistTrackDataCreate} from "@src/store/playlistTrackData";
import {useAudioPlayer} from "@src/store/music"
import MusicCard from "@src/components/musicCard"
import "./index.scss"
import {useRequest} from "ahooks";
import {songUrl} from "@src/services/music.ts";
import {useLocation} from "react-router-dom";

export interface PlaylistProps extends React.HTMLProps<HTMLDivElement> {
    isOpen: boolean; // 当前的显示状态
    setIsOpen: React.Dispatch<React.SetStateAction<boolean>>; // 用于改变状态的函数
}

//播放列表
export default function Playlist({isOpen, setIsOpen}: PlaylistProps) {
    const location = useLocation();
    const {songsList} = PlaylistTrackDataCreate()
    const {percentage, isPlaying, song, setSong, setSongUrlData, play} = useAudioPlayer()
    const songUrlApi = useRequest(songUrl, {manual: true});

    //跳转下一首歌
    function playNextSong(index: number) {
        // 计算下一首歌的索引，如果当前是最后一首歌，则回到第一首
        const nextIndex = (index + 1) % songsList.length;

        // 获取下一首歌的信息
        const nextSong = songsList[nextIndex];

        // 调用 API 获取歌曲播放链接
        songUrlApi.runAsync(nextSong.id)
            .then((data) => {
                // 设置当前播放的歌曲信息
                setSong(nextSong);
                // 设置歌曲的播放链接
                setSongUrlData(data);
                // 调用 play 方法开始播放
                play();
            })
    }

    //监听是否播放结束
    useEffect(() => {
        if (!isPlaying && percentage() == 100) {
            if (location.pathname.includes("/music")) {
                const index = songsList.findIndex(item => item.id === song.id)
                playNextSong(index)
            }
        }
    }, [isPlaying])

    return <Drawer position="bottom" height={"45%"} isOpen={isOpen} setIsOpen={setIsOpen}>
        <div className="Playlist">
            <h3>播放列表</h3>
            <ul>
                {songsList.map((songs) => (
                    <li key={songs.id}>
                        <div className="centered">
                            <MusicCard songs={songs}></MusicCard>
                        </div>
                    </li>
                ))}
                {songsList.length == 0 && <li>好像没有选择歌单呢 (●'◡'●)</li>}
            </ul>
        </div>
    </Drawer>
}